package project.dade.cn.bst.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.squareup.okhttp.Request;

import java.io.File;
import java.util.HashMap;

import butterknife.InjectView;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.Bimp;
import project.dade.cn.bst.utils.FileUtils;
import project.dade.cn.bst.utils.ImageFactory;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;

/**
 * Created by vain zhou on 2016/3/17.
 */
public class FeedBackActivity extends ZJPBaseBarActivity implements View.OnClickListener {
    @InjectView(R.id.spinner)
    Spinner spinner;
    @InjectView(R.id.et_content)
    EditText et_content;
//    @InjectView(R.id.gridview)
//    GridViewInScroll gridView;
    @InjectView(R.id.universal_toolBar)
    TextView toolbar;
    String level[] = {"普通反馈","购物投诉", "咨询求购","售后服务"};
    private ArrayAdapter<String> adapter;
    private GridAdapter gridAdapter;
    public String type;
    public int numerber;
    private KProgressHUD hud;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        Init();
    }

    private void Init() {
        adapter = new ArrayAdapter<String>(FeedBackActivity.this,
                android.R.layout.simple_spinner_dropdown_item);
        for (int i = 0; i < level.length; i++) {
            adapter.add(level[i]);
        }
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
//        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridAdapter = new GridAdapter(this);
        gridAdapter.update();
//        gridView.setAdapter(gridAdapter);
        toolbar.setOnClickListener(this);
//        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//                                    long arg3) {
//                if (Bimp.drr.size() == 0) {
//                    new PopupWindows(FeedBackActivity.this, gridView);
//
//                } else {
//                    if (Bimp.drr.size() == 4) {
//                        Intent intent = new Intent(FeedBackActivity.this,
//                                PhotoActivity.class);
//                        intent.putExtra("ID", arg2);
//                        startActivity(intent);
//                        finish();
//                    } else {
//                        if (arg2 == Bimp.drr.size()) {
//                            new PopupWindows(FeedBackActivity.this, gridView);
//                        } else {
//                            Intent intent = new Intent(FeedBackActivity.this,
//                                    PhotoActivity.class);
//                            intent.putExtra("ID", arg2);
//                            startActivity(intent);
//
//                        }
//                    }
//                }
//            }
//        });
        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                /* 将所选mySpinner 的值带入myTextView 中*/
//                myTextView.setText("您选择的是：" + adapter.getItem(arg2));
                type=adapter.getItem(arg2);
                /* 将mySpinner 显示*/
                numerber=arg2+1;
                arg0.setVisibility(View.VISIBLE);
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

                arg0.setVisibility(View.VISIBLE);
            }
        });

    }


    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 视图容器
        private int selectedPosition = -1;// 选中的位置
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            if (Bimp.drr.size() == 0) {
                return 1;
            } else if (Bimp.drr.size() < 4) {
                return (Bimp.drr.size() + 1);
            }
            return (Bimp.drr.size());
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return arg0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item设置
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            final int coord = position;
            ViewHolder holder = null;
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (Bimp.drr.size() == 0) {
                Glide.with(FeedBackActivity.this).load(R.drawable.icon_addpic_unfocused).into(holder.image);

            }
            if (Bimp.drr.size() == 4) {
                Glide.with(FeedBackActivity.this).load(Bimp.drr.get(position)).into(holder.image);

            } else {
                if (position == Bimp.drr.size()) {
                    Glide.with(FeedBackActivity.this).load(R.drawable.icon_addpic_unfocused).into(holder.image);
                } else {
                    Glide.with(FeedBackActivity.this).load(Bimp.drr.get(position)).into(holder.image);
                }
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        gridAdapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.drr.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            try {
                                if (Bimp.max >= 4) {
                                    break;
                                }
                                String path = Bimp.drr.get(Bimp.max);
                                System.out.println(path);
                                Bitmap bm = Bimp.revitionImageSize(path);
                                Bimp.bmp.add(bm);
                                String newStr = path.substring(
                                        path.lastIndexOf("/") + 1,
                                        path.lastIndexOf("."));
                                FileUtils.saveBitmap(bm, "" + newStr);
                                Bimp.max += 1;
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);

                            } catch (Exception e) {

                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        }
    }

    public String getString(String s) {
        String path = null;
        if (s == null)
            return "";
        for (int i = s.length() - 1; i > 0; i++) {
            s.charAt(i);
        }
        return path;
    }

    @Override
    protected void onResume() {
        gridAdapter.update();

        super.onResume();
    }

    public class PopupWindows extends PopupWindow {
        public PopupWindows(Context mContext, View parent) {

            View view = View
                    .inflate(mContext, R.layout.iem_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.FILL_PARENT);
            setHeight(ViewGroup.LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            TextView bt1 = (TextView) view
                    .findViewById(R.id.item_popupwindows_camera);
            TextView bt2 = (TextView) view
                    .findViewById(R.id.item_popupwindows_Photo);
            TextView bt3 = (TextView) view
                    .findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(FeedBackActivity.this,
                            PicActivity.class);
                    startActivity(intent);
                    finish();
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });

        }
    }


    private static final int TAKE_PICTURE = 0x000000;
    private String path = "";

    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File pfile = new File(Environment.getExternalStorageDirectory()
                + "/myimage");
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        File file = new File(pfile.getAbsolutePath(), String.valueOf(System.currentTimeMillis())
                + ".jpg");
        path = file.getPath();
        Uri imageUri = Uri.fromFile(file);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.drr.size() < 4 && resultCode == -1) {
                    Bimp.drr.add(path);
                    gridAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.universal_tool:
                this.finish();
                FileUtils.deleteDir();
            case R.id.universal_toolBar:
         if(!TextUtils.isEmpty(et_content.getText().toString().trim())) {
             requestLeaveWord();

            }else {
             ToastUtil.showShort(this, "输入框不能为空");
         }
                break;


        }

    }

    private void requestLeaveWord() {
        hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在加载")
                .setCancellable(true);
                hud.show();
        String str_content = et_content.getText().toString().trim();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("Type",numerber+"");
        params.put("Title",type);
        params.put("Content",str_content);
        OkHttpRequest.Builder okb = new OkHttpRequest.Builder();
        okb.url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.LeaveWord).params(params);
//        Pair<String, File>[] files = new Pair[Bimp.drr.size()];
//        for (int i = 0; i < Bimp.drr.size(); i++) {
//            LogUtil.i(TAG, "图片个数：" + "---------------------" + Bimp.drr.size());
//            File f = new File(Bimp.drr.get(i));
//            Bitmap bitmap1= ImageFactory.getBitmap(f.getAbsolutePath());
//            Bitmap bitmap2 = ImageFactory.ratio(bitmap1, 480, 800);
//            File f1= ImageFactory.saveMyBitmap(bitmap2);
//           Pair<String, File> filePair = Pair.create("FilePath" + i, f1);//key是对应图片上环的参数名称
//            files[i] = filePair;
//        }
  //      okb.files(files);

        okb.upload(new ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                    hud.dismiss();
                ToastUtil.showShort(FeedBackActivity.this, "网络相应失败请稍后再试");
            }

            @Override
            public void onResponse(String response) {
                if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取收货地址"))) {
                    hud.dismiss();
                    BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);

                    if (model != null && model.getResult() == 0) {
                        LogUtil.i(TAG, "上传成功" + model.getData());
                        ToastUtil.showShort(FeedBackActivity.this, "提交成功");
                         finish();
                    }

                } else {
                    hud.dismiss();
                    ToastUtil.showShort(FeedBackActivity.this, NetRequestUtil.requestsError(response, "失败"));

                }
            }

        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            FileUtils.deleteDir();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
